package com.example.nick.bodyapplication.log;

import android.text.TextUtils;
import android.util.Log;

public class MLog {
   public static final String NULL_TIPS = "Log with null object";
   private static final String DEFAULT_MESSAGE = "execute";
   private static final String PARAM = "Param";
   private static final String NULL = "null";
   private static final String TAG_DEFAULT = "KLog";
   private static final String SUFFIX = ".java";
   private static String mGlobalTag;
   private static boolean mIsGlobalTagEmpty = true;
   private static boolean IS_SHOW_LOG = true;

   public static void logI(String iTag, String iMsg) {
      String[] contents = wrapperContent(4, iTag, iMsg);
      String tag = contents[0];
      String msg = contents[1];
      String headString = contents[2];
      Log.i(tag, msg + headString);
   }

   private static String[] wrapperContent(int stackTraceIndex, String tagStr, Object... objects) {

      StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();

      StackTraceElement targetElement = stackTrace[stackTraceIndex];
      String className = targetElement.getClassName();
      String[] classNameInfo = className.split("\\.");
      if (classNameInfo.length > 0) {
         className = classNameInfo[classNameInfo.length - 1] + SUFFIX;
      }

      if (className.contains("$")) {
         className = className.split("\\$")[0] + SUFFIX;
      }

      String methodName = targetElement.getMethodName();
      int lineNumber = targetElement.getLineNumber();

      if (lineNumber < 0) {
         lineNumber = 0;
      }

      String tag = (tagStr == null ? className : tagStr);

      if (mIsGlobalTagEmpty && TextUtils.isEmpty(tag)) {
         tag = TAG_DEFAULT;
      } else if (!mIsGlobalTagEmpty) {
         tag = mGlobalTag;
      }

      String msg = (objects == null) ? NULL_TIPS : getObjectsString(objects);
      String headString = "[ (" + className + ":" + lineNumber + ")#" + methodName + " ] ";
      Log.e("log", className+"/"+lineNumber+"/"+methodName);
      return new String[]{tag, msg, headString};
   }

   private static String getObjectsString(Object... objects) {

      if (objects.length > 1) {
         StringBuilder stringBuilder = new StringBuilder();
         stringBuilder.append("\n");
         for (int i = 0; i < objects.length; i++) {
            Object object = objects[i];
            if (object == null) {
               stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ").append(NULL).append("\n");
            } else {
               stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ").append(object.toString()).append("\n");
            }
         }
         return stringBuilder.toString();
      } else if (objects.length == 1) {
         Object object = objects[0];
         return object == null ? NULL : object.toString();
      } else {
         return NULL;
      }
   }
}
